package com.huang.gateway.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huang.gateway.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author hqy
 * @date 2022年06月20日 9:43
 */
@Configuration
public class GatewayRouterConfig {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder){
        return builder
                .routes()
                .route(r->r.path("/sys/menu/nav").uri("lb://manager-service"))
                .route(r->r.path("/oauth/token")
                        .filters(f->f.modifyResponseBody(String.class,String.class,(exchange,result)->{

                            Assert.notNull(result,"参数为空，，不能存储");

                            JSONObject jsonObject = JSON.parseObject(result);
                            String access_token = jsonObject.getString("access_token");
                            Integer expires_in = jsonObject.getInteger("expires_in");

                            stringRedisTemplate.opsForValue().set(GatewayConstant.TOKEN_PREFIX + access_token,"", Duration.ofSeconds(expires_in));
                            return Mono.just(result);
                        }))
                        .uri("lb://oauth-server"))
                .build();

    }
}
